"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 可靠性-数据库系统类
Case Name   : 修改审计文件后，启动数据库
Create At   : 2022/6/21
Owner       : @li-xin12345
Description :
    1.执行登入退出，做审计操作
    2.执行过程中修改审计文件
      echo 1 > 0_adt
    3.重启数据库
     gs_om –t stop
     gs_om –t start
    4.恢复参数
Expect      :
    1.执行登入退出，做审计操作成功
    2.修改审计文件成功
    3.重启数据库成功
    4.恢复参数
History     :
"""
import os
import unittest
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.ComThread import ComThread
from testcase.utils.CommonSH import RestartDbCluster
from yat.test import Node
from yat.test import macro


class Dbsys(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.logger = Logger()
        self.logger.info(f"-----{os.path.basename(__file__)} start-----")
        self.primary_node = Node('PrimaryDbUser')
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.common = Common()
        self.dirpath = os.path.join(macro.PG_AUDIT_PATH,
                                    'audit_log_dbsys_case058')
        audit_dir_msg = self.primary_sh.executDbSql('show audit_directory;')
        self.logger.info(audit_dir_msg)
        self.audit_dir_default = audit_dir_msg.splitlines()[-2].strip()

    def test_dbsys(self):
        text = '-----step1:执行登入退出，做审计操作;expect:执行登入退出，做审计操作成功-----'
        self.logger.info(text)
        self.logger.info('-----修改审计日志目录为其他目录，方便查看-----')
        result = self.primary_sh.executeGsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f"audit_directory='{self.dirpath}'")
        self.assertTrue(result, '执行失败' + text)
        stop_msg = self.primary_sh.stopDbCluster()
        self.logger.info(stop_msg)
        self.assertTrue(stop_msg, '停库失败')
        start_res = self.primary_sh.startDbCluster()
        self.logger.info(start_res)
        self.assertTrue(start_res, '启动失败')
        show_msg = self.primary_sh.executDbSql('show audit_directory;')
        self.logger.info(show_msg)
        self.assertEquals(self.dirpath, show_msg.splitlines()[-2].strip(),
                          '执行失败' + text)
        self.logger.info('-----执行登入退出-----')
        threads = []
        login_exit_cmd = f'source {macro.DB_ENV_PATH};' \
            f'for i in {{1..1000}};' \
            f'do gsql -d postgres -p {self.primary_node.db_port} ' \
            f'-r -c "\\q" & done'
        self.logger.info(login_exit_cmd)
        thread_1 = ComThread(self.common.get_sh_result, args=(login_exit_cmd,))
        threads.append(thread_1)

        self.logger.info('-----查看审计记录-----')
        sql_cmd = f"select pg_sleep(1);" \
            f"select * from pg_query_audit(now()-interval '10 s',now());"
        self.logger.info(sql_cmd)
        thread_2 = ComThread(self.primary_sh.executDbSql, args=(sql_cmd,))
        threads.append(thread_2)

        text = '-----step2:执行过程中修改审计文件;expect:修改审计文件成功-----'
        self.logger.info(text)
        shell_cmd = f'''sleep 1;ls -t {self.dirpath} | grep _adt'''
        self.logger.info(shell_cmd)
        shell_msg = self.primary_node.sh(shell_cmd).result()
        self.logger.info(shell_msg)
        audit_log = os.path.join(self.dirpath, shell_msg)
        self.logger.info(audit_log)
        echo_cmd = f'sleep 2; echo 1 > {audit_log} '
        self.logger.info(echo_cmd)
        thread_3 = ComThread(self.common.get_sh_result, args=(echo_cmd,))
        threads.append(thread_3)
        for thread in threads:
            thread.setDaemon(True)
            thread.start()
        for thread in threads:
            thread.join(60)
            self.logger.info(thread.get_result())
            if thread == thread_2:
                self.assertIn('login_success' and 'user_logout',
                              thread.get_result(), '执行失败' + text)
            else:
                self.assertIsNone(thread.get_result(), '执行失败' + text)

        text = '-----step3:重启数据库;expect:重启数据库成功-----'
        self.logger.info(text)
        stop_msg = self.primary_sh.stopDbCluster()
        self.logger.info(stop_msg)
        self.assertTrue(stop_msg, '停库失败')
        start_res = self.primary_sh.startDbCluster()
        self.logger.info(start_res)
        self.assertTrue(start_res, '启动失败')

    def tearDown(self):
        text = '-----step4:恢复参数;expect:恢复参数成功-----'
        self.logger.info(text)
        result = self.primary_sh.executeGsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f"audit_directory='{self.audit_dir_default}'")
        stop_msg = self.primary_sh.stopDbCluster()
        self.logger.info(stop_msg)
        start_res = self.primary_sh.startDbCluster()
        self.logger.info(start_res)
        show_msg = self.primary_sh.executDbSql('show audit_directory;')
        self.logger.info(show_msg)

        self.logger.info('-----断言tearDown-----')
        self.assertTrue(result, '执行失败' + text)
        self.assertTrue(stop_msg, '停库失败')
        self.assertTrue(start_res, '启动失败')
        self.assertEquals(self.audit_dir_default,
                          show_msg.splitlines()[-2].strip(), '执行失败' + text)
        self.logger.info(f"-----{os.path.basename(__file__)} end-----")
